#include<ws2tcpip.h>
#include <iostream>
#include <string>
#include <conio.h>
#include <thread>
#pragma comment (lib, "ws2_32.lib")
using namespace std;

void heart(SOCKET clientSocket)
{
	while (true)
	{
		Sleep(5000);
		string tempdata = "Send heartbeat packet from client1";
		int result = send(clientSocket, tempdata.c_str(), tempdata.length() + 1, 0);
		if (result<0)
		{
			cout << "Server socket close\n";
			break;
		}
	}
}

int main()
{
	int err;
	WORD versionRequired;
	WSADATA wsaData;
	versionRequired = MAKEWORD(1, 1);
	err = WSAStartup(versionRequired, &wsaData);
	if (!err)
	{
		cout << LPSTR("Client socket open successfully\n");
	}
	else
	{
		cout << ("Client socket open fail for ") << WSAGetLastError() << endl;
		return 0;
	}
	SOCKET clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	SOCKADDR_IN clientsock_in;
	inet_pton(AF_INET,"127.0.0.1", &clientsock_in.sin_addr);
	clientsock_in.sin_family = AF_INET;
	clientsock_in.sin_port = htons(3000);
	int fail = connect(clientSocket, (SOCKADDR*)&clientsock_in, sizeof(SOCKADDR));
	if (fail) {
		cout << "Connect to server fail." << endl;
		_getch();
		return 0;
	}
	string s;
	thread t(heart,clientSocket);
	t.join();
	while (cin >> s) {
		char receiveBuf[100];
		recv(clientSocket, receiveBuf, 101, 0);
		cout << receiveBuf << endl;
		send(clientSocket, s.c_str(), s.length() + 1, 0);
		if (s == "end") {
			break;
		}
	}
	closesocket(clientSocket);
	if (WSACleanup() == SOCKET_ERROR) {
		cout << "Socket close fail for" << WSAGetLastError() << endl;
	}
	else {
		cout << "Socket close successfully" << endl;
	}
	_getch();
	return 0;
}